using System;
using System.Linq;

namespace UMC.Net;


public class NetLoger
{
    int _SizeType;
    public int SizeType => _SizeType;
    public ByteChunk Chunk => _byteChunk;
    protected ByteChunk _byteChunk;
    public NetLoger(ByteChunk byteChunk)
    {
        this._byteChunk = byteChunk;
    }
    protected int _startIndex = 0;

    public NetLoger Info()
    {
        return Log(0x01);
    }
    public NetLoger Warn()
    {
        return Log(0x02);
    }
    public NetLoger Debug()
    {
        return Log(0x03);

    }
    protected void SetSizeType(byte b)
    {
        _SizeType = _SizeType | (int)Math.Pow(2, b);
    }
    public NetLoger Error()
    {
        return Log(0x04);
    }
    public NetLoger Write(ReadOnlySpan<byte> stringValue)
    {
        if (this._type > 0)
            this._byteChunk.Temp(stringValue);
        return this;
    }
    public NetLoger Write(string stringValue)
    {
        if (this._type > 0)
            this._byteChunk.Temp(stringValue);
        return this;
    }
    public NetLoger Write(string str, out StringValue stringValue)
    {
        int t = this._byteChunk.TempSize;
        int s = this._byteChunk.Temp(str);
        stringValue = this._byteChunk.Segment(this._byteChunk.Size + t, s);
        return this;
    }
    public const int MaxLogLength = 0xfff;
    public void End()
    {
        var ts = _byteChunk.TempSize;
        if (ts > 0)
        {
            ts -= 2;
            if (ts > MaxLogLength)
            {
                this._byteChunk.Scale(ts - MaxLogLength);
                ts = MaxLogLength;
            }
            ushort t = (ushort)ts;
            var span = this._byteChunk.Chunk.AsSpan(this._startIndex, 2);
            BitConverter.TryWriteBytes(span, t);
            span.Reverse();
            SetSizeType(this._type);
            byte v = (byte)(this._type << 4);
            this._byteChunk.Chunk[_startIndex] += v;
            this._byteChunk.Temp();

        }
    }
    protected byte _type;
    protected NetLoger Log(byte type)
    {

        this.End();
        this._type = type;

        this._startIndex = this._byteChunk.Size;
        this._byteChunk.Temp(type);
        this._byteChunk.Temp(type);
        this._type = type;
        return this;// new NetLoger(this._byteChunk, this._byteChunk.Size, type);
    }

}